package com.das.mechanic_base.utils;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Rect;
import android.media.MediaMetadataRetriever;
import android.net.Uri;
import android.os.Environment;
import android.os.StatFs;
import android.provider.MediaStore;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.ScrollView;

import androidx.exifinterface.media.ExifInterface;

import com.coremedia.iso.boxes.Container;
import com.das.mechanic_base.app.X3Constent;
import com.das.mechanic_base.app.X3MyApp;
import com.das.mechanic_base.bean.alone.RecordBean;
import com.das.mechanic_base.gen.AddTagBeanDao;
import com.das.mechanic_base.gen.AloneImageBeanDao;
import com.das.mechanic_base.gen.AloneSearchBeanDao;
import com.das.mechanic_base.gen.CustomRecordListBeanDao;
import com.das.mechanic_base.gen.DaoSession;
import com.das.mechanic_base.gen.MineRecordBeanDao;
import com.das.mechanic_base.gen.WorkNewImageBeanDao;
import com.googlecode.mp4parser.authoring.Movie;
import com.googlecode.mp4parser.authoring.Track;
import com.googlecode.mp4parser.authoring.builder.DefaultMp4Builder;
import com.googlecode.mp4parser.authoring.container.mp4.MovieCreator;
import com.googlecode.mp4parser.authoring.tracks.AppendTrack;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.hjq.toast.ToastUtils;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStreamWriter;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.channels.FileChannel;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;

import io.reactivex.Observable;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;


/**
 * Created by chensi on 2018/5/4.
 */

public class X3FileUtils {

    // 存储车辆缩略图
    public static String CAR_STORAGE_PATH = "/car/";

    // 存储apk的安装位置
    public static String APP_STORAGE_PATH = "/app/";

    //  存储录音的位置
    public static String RECORD_STORAGE_PATH = "/mechanic_record/";

    //  检测保存图片
    public static String MECHANIC_PHOTO_STORAGE_PATH = "/mechanic_photo/";

    //  检测保存视频
    public static String MECHANIC_VIDEO_STORAGE_PATH = "/mechanic_video/";

    //  检测存储题目
    public static String ALONE_STORAGE_PATH ="/Alone/";

    // 外部可见存储的图片
    public static String MECHANIC_SAVE_STORAGE_PATH = "/mechanic_save/";

    //vin图片
    public static String MECHANIC_SAVE_VIN_PATH = "/mechanic_vin/";

    //施工记录检测报告截图保存地址
    public static String MECHANIC_SCREEN_SHOT_STORAGE_PATH = "/mechanic_screen_shot/";

    //  网络测速文件保存地址
    public static String NET_CHECK_FILE_PATH = "/mechanic_net_check/";

    public static String distoryName = "/member/";
    private static File file;

    /**
     * 获取存储地址基本
     * @param mContext
     * @return
     */
    private static String getBaseStoragePath(Context mContext) {
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            // 检测外置SD卡是否可用
            return mContext.getExternalCacheDir().getAbsolutePath();
        }
        return mContext.getCacheDir().getAbsolutePath();
    }

    /**
     * 获取要存储那个文件夹
     * @return
     */
    public static String getStoragePath(Context mContext,String path) {
        String storagePath = getBaseStoragePath(mContext) + path;
        File storageFile = new File(storagePath);
        if (storagePath.endsWith(".mp3") || storagePath.endsWith(".mp4") || storagePath.endsWith(".wav")
                || storagePath.endsWith(".jpg") || storagePath.endsWith(".png") || storagePath.endsWith(".apk")
                || storagePath.endsWith(".jpeg")) {
            if (!storageFile.exists()) {
                try {
                    storageFile.createNewFile();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }else {
            if (!storageFile.exists()) {
                storageFile.mkdirs();
            }
        }
        return storagePath;
    }


    /**
     * 将数据存到文件中
     * @param context context
     * @param data 需要保存的数据
     * @param fileName 文件名
     */
    public static void saveDataToFile(Context context, String data, String fileName){

        FileOutputStream fileOutputStream = null;
        BufferedWriter bufferedWriter = null;
        try {
            /**
             * "data"为文件名,MODE_PRIVATE表示如果存在同名文件则覆盖，
             * 还有一个MODE_APPEND表示如果存在同名文件则会往里面追加内容
             */
            fileOutputStream = context.openFileOutput(fileName,
                    Context.MODE_PRIVATE);
            bufferedWriter = new BufferedWriter(new OutputStreamWriter(fileOutputStream));
            bufferedWriter.write(data);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (bufferedWriter != null) {
                    bufferedWriter.close();
                }
                if (fileOutputStream != null) {
                    fileOutputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 读取sd卡对象
     *
     * @param fileName 文件名
     * @return
     */
    @SuppressWarnings("unchecked")
    public static String readFromSdCard(String path, String fileName) {
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {  //检测sd卡是否存在

            String content = "";

            File file = new File(path, fileName);

            if (!file.exists()) {
                return content;
            }
            InputStream instream = null;
            try {
                instream = new FileInputStream(file);
                if (instream != null) {
                    InputStreamReader inputreader = new InputStreamReader(instream);
                    BufferedReader buffreader = new BufferedReader(inputreader);
                    String line;
                    //分行读取
                    while ((line = buffreader.readLine()) != null) {
                        content = content + line;
                    }
                    return content;
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (instream != null) {
                    try {
                        instream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        return null;
    }

    /**
     * 从文件中读取数据
     * @param context context
     * @param fileName 文件名
     * @return 从文件中读取的数据
     */
    public static String loadDataFromFile(Context context, String fileName) {
        FileInputStream fileInputStream = null;
        BufferedReader bufferedReader = null;
        StringBuilder stringBuilder = new StringBuilder();
        try
        {
            /**
             * 注意这里的fileName不要用绝对路径，只需要文件名就可以了，系统会自动到data目录下去加载这个文件
             */
            fileInputStream = context.openFileInput(fileName);
            bufferedReader = new BufferedReader(
                    new InputStreamReader(fileInputStream));
            String result = "";
            while ((result = bufferedReader.readLine()) != null) {
                stringBuilder.append(result);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (fileInputStream != null) {
                    fileInputStream.close();
                }
                if (bufferedReader != null) {
                    bufferedReader.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return stringBuilder.toString();
    }

    /**
     * @param path
     * @return
     * @throws IOException
     * 压缩图片
     */
    public static Bitmap revitionImageSize(String path) throws IOException {
        //根据文件路径,创建一个字节缓冲输入流
        BufferedInputStream in = new BufferedInputStream(new FileInputStream(
                new File(path)));
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        //根据流返回一个位图也就是bitmap，当options.inJustDecodeBounds = true的时候不需要完全解码，
        // 它仅仅会把它的宽，高取回来给你，这样就不会占用太多的内存，也就不会那么频繁的发生OOM了
        BitmapFactory.decodeStream(in, null, options);
        //关闭流
        in.close();
        int i = 0;
        Bitmap bitmap = null;
        while (true) {
            // options.outWidth >> i 。右移运算符，num >> 1,相当于num除以2
            if ((options.outWidth >> i <= 1000) && (options.outHeight >> i <= 1000)) {
                //得到一个输入流
                in = new BufferedInputStream(new FileInputStream(new File(path)));
                //为了解决图片解码时候出现SanpleSize错误，设置恰当的inSampleSize可以使BitmapFactory分配更少的空间以消除该错误
                //你将 inSampleSize 赋值为2,那就是每隔2行采1行,每隔2列采一列,那你解析出的图片就是原图大小的1/4.
                // Math.pow(2.0D, i)次方运算，2的i次方是多少
                options.inSampleSize = (int) Math.pow(2.0D, i);
                // 这里之前设置为了true，所以要改为false，否则就创建不出图片
                options.inJustDecodeBounds = false;
                bitmap = BitmapFactory.decodeStream(in, null, options);
                break;
            }
            i += 1;
        }
        return bitmap;
    }

    /**
     * 将集合写入sd卡
     *
     * @param fileName 文件名
     * @param list     集合
     * @return true 保存成功
     */
    public static void writeListIntoSDcard(String fileName, List<String> list,String filePath) {

        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            File sdFile = new File(filePath, fileName);
            FileOutputStream fos = null;
            ObjectOutputStream oos = null;
            try {
                fos = new FileOutputStream(sdFile);
                oos = new ObjectOutputStream(fos);
                oos.writeObject(list);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }finally {

                try {
                    if (fos != null) {
                        fos.close();
                    }

                } catch (IOException e) {
                    e.printStackTrace();
                }
                try {
                    if (oos != null) {
                        oos.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 将集合写入sd卡
     *
     * @param fileName 文件名
     * @param list     集合
     * @return true 保存成功
     */
    public static void writeListSDcard(String filePath,String fileName, RecordBean list) {

        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            File sdFile = new File(filePath, fileName);
            FileOutputStream fos = null;
            ObjectOutputStream oos = null;
            try {
                fos = new FileOutputStream(sdFile);
                oos = new ObjectOutputStream(fos);
                oos.writeObject(list);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }finally {

                try {
                    if (fos != null) {
                        fos.close();
                    }

                } catch (IOException e) {
                    e.printStackTrace();
                }
                try {
                    if (oos != null) {
                        oos.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 读取sd卡对象
     *
     * @param fileName 文件名
     * @return
     */
    @SuppressWarnings("unchecked")
    public static RecordBean readRecordSdCard(String filePath,String fileName) {
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {  //检测sd卡是否存在
            RecordBean list;
            File sdFile = new File(filePath, fileName);
            FileInputStream fis = null;
            ObjectInputStream ois = null;
            try {
                fis = new FileInputStream(sdFile);
                ois = new ObjectInputStream(fis);
                list = (RecordBean) ois.readObject();
                return list;
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            } finally {
                try {
                    if (fis != null) {
                        fis.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
                try {
                    if (ois != null) {
                        ois.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        } else {
            return null;
        }
    }

    /**
     * 读取sd卡对象
     *
     * @param fileName 文件名
     * @return
     */
    @SuppressWarnings("unchecked")
    public static List<String> readListFromSdCard(String path,String fileName) {
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {  //检测sd卡是否存在
            List<String> list;
            File sdFile = new File(path, fileName);
            FileInputStream fis = null;
            ObjectInputStream ois = null;
            try {
                fis = new FileInputStream(sdFile);
                ois = new ObjectInputStream(fis);
                list = (List<String>) ois.readObject();
                return list;
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            } finally {
                try {
                    if (fis != null) {
                        fis.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
                try {
                    if (ois != null) {
                        ois.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        } else {
            return null;
        }
    }

    /**
     * 删除指定文件
     */
    public static void deleteFiles (Context context,String fileName) {

        File f = new File(Environment.getExternalStorageDirectory()+"");
        File[] fl = f.listFiles();
        if (fl != null && fl.length > 0) {
            for (int i = 0; i < fl.length; i++) {
                if (fl[i].getName().contains(fileName)) {
                    fl[i].delete();
                }
            }
        }

        File file = new File(context.getFilesDir().getPath());
        File[] files = file.listFiles();
        if (files != null && files.length > 0) {
            for (int i = 0; i < files.length; i++) {
                if (files[i].getName().contains(fileName)) {
                    files[i].delete();
                }
            }
        }
    }

    /**
     * 获取指定文件大小
     * @return
     * @throws 　　
     */
    public static long getFileSize(Context context,String filePath,String fileName) throws Exception {
        long size = 0;
        File f = new File(getBaseStoragePath(context) + filePath);
        FileInputStream fis = null;

        if (f != null) {
            File[] fl = f.listFiles();
            if (fl != null) {
                for (int i = 0; i < fl.length; i++) {
                    if (fl[i].getName() != null && !"".equals(fl[i].getName())) {
                        if (fl[i].getName().contains(fileName)) {
                            fis = new FileInputStream(fl[i]);
                            size = size + fis.available();
                        }
                    }
                }
            }
        }

        if (fis != null) {
            fis.close();
        }
        return size;
    }

    /**
     * 将json写入sd卡
     *
     * @return true 保存成功
     */
    public static void writeServiceSDcard(String path, String s, String fileName) {

        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {

            File file = new File(path);
            if (!file.exists()) {
                file.mkdirs();
            }

            File file2 = new File(path);
            if (!file2.exists()) {
                try {
                    file.mkdirs();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            File file1 = new File(file.getAbsolutePath(), fileName);
            FileOutputStream outStream = null;
            try {
                file1.createNewFile();

            } catch (Exception e) {
                e.printStackTrace();
            }
            try {
                outStream = new FileOutputStream(file1);
                outStream.write(s.getBytes());
                outStream.flush();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (outStream != null) {
                    try {
                        outStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    /**
     * 将json写入sd卡
     *
     * @return true 保存成功
     */
    public static void writeJsonIntoSDcard(String path, String s, String fileName) {
        if (X3StringUtils.isEmpty(s)) {
            return;
        }
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {

            File file = new File(path);
            if (!file.exists()) {
                file.mkdirs();
            }

            File file1 = new File(file.getAbsolutePath(), fileName);

            FileOutputStream outStream = null;
            if (!file1.exists()) {
                try {
                    file1.createNewFile();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            try {
                outStream = new FileOutputStream(file1);

                outStream.write(s.getBytes());
                outStream.flush();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (outStream != null) {
                    try {
                        outStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    /**
     * 将json写入sd卡
     *
     * @return true 保存成功
     */
    public static void writeIntoSDcard(String path, String s, String fileName) {

        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {

            File file = new File(path);
            if (!file.exists()) {
                file.mkdirs();
            }

            File file1 = new File(file.getAbsolutePath(), fileName);
            FileOutputStream outStream = null;
            try {
                file1.createNewFile();

            } catch (Exception e) {
                e.printStackTrace();
            }
            try {
                outStream = new FileOutputStream(file1);
                outStream.write(s.getBytes());
                outStream.flush();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (outStream != null) {
                    try {
                        outStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    public static Bitmap zoomImage(Bitmap bgimage, double newWidth, double newHeight) {
        // 获取这个图片的宽和高
        float width = bgimage.getWidth();
        float height = bgimage.getHeight();
        // 创建操作图片用的matrix对象
        Matrix matrix = new Matrix();
        // 计算宽高缩放率
        float scaleWidth = ((float) newWidth) / width;
        float scaleHeight = ((float) newHeight) / height;
        // 缩放图片动作
        //matrix.postScale(scaleWidth, scaleHeight);
        Bitmap bitmap = Bitmap.createBitmap(bgimage, 0, 0, (int) width,
                (int) height, matrix, true);
        return bitmap;
    }

    /**
     * 截取指定View为图片
     *
     * @param view
     * @return
     * @throws Throwable
     */
    public static Bitmap captureView(View view) throws Throwable {
        Bitmap bm = Bitmap.createBitmap(view.getWidth(), view.getHeight(), Bitmap.Config.ARGB_8888);
        view.draw(new Canvas(bm));
        return bm;
    }

    /**
     * 转换文件大小
     * @param fileS
     * @return
     *
     */
    public static String FormetFileSize(long fileS) {
        //DecimalFormat df = new DecimalFormat("#.00");
        String wrongSize = "0B";
        String fileSizeString = "";
        if (fileS == 0) {
            return wrongSize;
        }

        if (fileS < 1024) {
            fileSizeString = (int) fileS + "B";
        } else if (fileS < 1048576) {
            fileSizeString = ((int) (fileS / 1024)) + "KB";
        } else if (fileS < 1073741824) {
            fileSizeString = ((int) (fileS / 1048576)) + "MB";
        } else {
            fileSizeString = ((int) (fileS / 1073741824)) + "GB";
        }
        return fileSizeString;
    }

    /**
     * 判断文件是否存在
     */
    public static boolean fileExist(String fileName) {
        File file = new File(fileName);
        file.isFile();
        return file.exists();
    }

    public static String saveBitmap(String imgPath, String fileName, Bitmap bitmap) {
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            File file = new File(imgPath);
            if (!file.exists()) {
                file.mkdirs();
            }

            File file1 = new File(file.getAbsolutePath(), fileName);
            FileOutputStream out = null;
            if (!file1.exists()) {
                try {
                    file1.createNewFile();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            try {
                out = new FileOutputStream(file1);

                bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);

                out.flush();

                return file1.getPath();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (out != null) {
                    try {
                        out.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        return "";

    }

    /**
     * 保存图片并且刷新到相册中
     * @param mContext
     * @param fileName
     * @param bitmap
     * @return
     */
    public static File saveBitmapToCamera(Context mContext,String fileName, Bitmap bitmap) {
        String parentPath = Environment.getExternalStorageDirectory().getPath() + "/DCIM/Camera/";
        File parentFile = new File(parentPath);
        if (!parentFile.exists()) {
            parentFile.mkdirs();
        }

        String filePath = Environment.getExternalStorageDirectory().getPath() + "/DCIM/Camera/" + fileName;
        File file = new File(filePath);
        if (bitmap == null) {
            return file;
        }

        file.getParent();

        if (file.exists()) {
            file.delete();
        }
        FileOutputStream out;
        try {
            out = new FileOutputStream(file);
            // 格式为 JPEG，照相机拍出的图片为JPEG格式的，PNG格式的不能显示在相册中
            if (bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out)) {
                out.flush();
                out.close();
                // 插入图库
                MediaStore.Images.Media.insertImage(mContext.getContentResolver(), file.getAbsolutePath(), fileName, null);
            }
            return file;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return parentFile;
    }

    public static String getRealPathFromURI(Context context, Uri contentURI) {
        String result;
        Cursor cursor = context.getContentResolver().query(contentURI, null, null, null, null);
        if (cursor == null) { // Source is Dropbox or other similar local file path
            result = contentURI.getPath();
        } else {
            cursor.moveToFirst();
            int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
            result = cursor.getString(idx);
            cursor.close();
        }
        return result;
    }

    // 将字符串写入到文本文件中
    public static void writeTxtToFile(String content, String filePath, String fileName) {
        //生成文件夹之后，再生成文件，不然会出错
        makeFilePath(filePath, fileName);

        String strFilePath = filePath + fileName;
        FileOutputStream fileOutputStream = null;
        BufferedWriter bufferedWriter = null;
        try {
            File file = new File(strFilePath);
            Log.d("TestFile", "Create the file:" + strFilePath);
            file.getParentFile().mkdirs();
            file.createNewFile();

            fileOutputStream = new FileOutputStream(file);
            bufferedWriter = new BufferedWriter(new OutputStreamWriter(fileOutputStream));
            bufferedWriter.write(content);

        } catch (Exception e) {
            Log.e("TestFile", "Error on write File:" + e);
        }finally {
            try {
                if (bufferedWriter != null) {
                    bufferedWriter.close();
                }
                if (fileOutputStream != null) {
                    fileOutputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    // 生成文件
    private static File makeFilePath(String filePath, String fileName) {
        File file = null;
        makeRootDirectory(filePath);
        try {
            file = new File(filePath + fileName);
            file.createNewFile();

        } catch (Exception e) {
            e.printStackTrace();
        }
        return file;
    }

    // 生成文件夹
    private static void makeRootDirectory(String filePath) {
        File file = null;
        try {
            file = new File(filePath);
            if (!file.exists()) {
                file.mkdir();
            }
        } catch (Exception e) {
        }
    }
    /**
     * 将头像写入sdk
     */
    public static void saveHeadUrl(Context mContext,String headUrl, String type) {

        Bitmap bitmap = null;
        //下载图片的路径
        try {
            //对资源链接
            URL url = new URL(headUrl);
            //打开输入流
            InputStream inputStream = url.openStream();
            //对网上资源进行下载转换位图图片
            bitmap = BitmapFactory.decodeStream(inputStream);
            // handler.sendEmptyMessage(111);
            inputStream.close();

            //再一次打开
            inputStream = url.openStream();
            if ("driHead".equals(type)) {
                file = new File(getStoragePath(mContext, X3FileUtils.APP_STORAGE_PATH) + "drihead.jpg");

            } else {
                file = new File(getStoragePath(mContext, X3FileUtils.APP_STORAGE_PATH) + "minhead.jpg");

            }
            FileOutputStream fileOutputStream = new FileOutputStream(file);
            int hasRead = 0;
            while ((hasRead = inputStream.read()) != -1) {
                fileOutputStream.write(hasRead);
            }
            fileOutputStream.close();
            inputStream.close();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (!"driHead".equals(type)) {
            }
        }

    }

    public static void deleteDir(String path) {
        deleteDirWihtFile(new File(path));
    }

    //删除文件及文件夹
    public static void deleteDirWihtFile(File dir)
    {
        if (dir == null || !dir.exists() || !dir.isDirectory())
        {
            return;
        }
        for (File file : dir.listFiles()) {
            if (file.isFile())
            {
                file.delete(); // 删除所有文件
            }
            else if (file.isDirectory())
            {
                deleteDirWihtFile(file); // 递规的方式删除文件夹
            }
        }
        dir.delete();// 删除目录本身
    }

    /**
     * 获取指定文件夹大小
     * @return
     * @throws 　　
     */
    public static long getFileFolderSize(Context mContext,String filePath) throws Exception {
        int size = 0;
        File f = new File(getBaseStoragePath(mContext) + filePath);

        if (!f.exists()) {
            return 0;
        }
        FileInputStream fis = null;
        if (f != null) {
            File[] fl = f.listFiles();
            if (fl != null) {
                for (int i = 0; i < fl.length; i++) {
                    if (fl[i].isDirectory()) {
                        break;
                    }
                    fis = new FileInputStream(fl[i]);
                    size = size + fis.available();
                }
            }
        }

        if (fis != null) {
            fis.close();
        }
        return size;
    }

    /**
     * 删除文件夹下的内容
     * @param folderFile
     */
    public static void deleteFolderFiles (File folderFile) {
        if (folderFile == null) {
            return;
        }
        if (!folderFile.exists()) {
            return;
        }

        folderFile.delete();
    }

    /**
     * 清理app缓存
     */
    public static void clearAppCache(Context mContext) {
        deleteDir(getStoragePath(mContext, X3FileUtils.RECORD_STORAGE_PATH));
        deleteDir(getStoragePath(mContext, X3FileUtils.MECHANIC_PHOTO_STORAGE_PATH));
        deleteDir(getStoragePath(mContext, X3FileUtils.MECHANIC_VIDEO_STORAGE_PATH));
        deleteDir(getStoragePath(mContext, X3FileUtils.ALONE_STORAGE_PATH));
        deleteDir(getStoragePath(mContext, X3FileUtils.CAR_STORAGE_PATH));
        deleteDir(getStoragePath(mContext, X3FileUtils.APP_STORAGE_PATH));
        deleteDir(getStoragePath(mContext, X3FileUtils.RECORD_STORAGE_PATH));
    }

    private static final String mformatType = "yyyy-MM-dd HH:mm:ss";

    public static String getFileLastModifiedTime(File file) {
        Calendar cal = Calendar.getInstance();
        long time = file.lastModified();
        SimpleDateFormat formatter = new SimpleDateFormat(mformatType);
        cal.setTimeInMillis(time);

        // 输出：修改时间[2] 2009-08-17 10:32
        return formatter.format(cal.getTime());
    }

    /**
     * 获取文件名字 不带后缀
     * @param filename
     * @return
     */
    public static String getExtensionName(String filename) {
        if ((filename != null) && (filename.length() > 0)) {
            int dot = filename.lastIndexOf('.');
            if ((dot >-1) && (dot < (filename.length() - 1))) {
                return filename.substring(0,dot);
            }
        }
        return filename;
    }


    /**
     * 获取sd卡剩余空间
     * @return
     */
    public static long getTotalSize() {
        if(Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
            //获得Sdcard上每个block的size
            File file= Environment.getExternalStorageDirectory();
            StatFs statFs=new StatFs(file.getPath());
            long blockSize = statFs.getBlockSizeLong();
            //获取可供程序使用的Block数量
            long blockavailable = statFs.getAvailableBlocksLong();
            //计算标准大小使用：1024，当然使用1000也可以
            long blockavailableTotal = blockSize * blockavailable/1000/1000;
            return blockavailableTotal;

        }else {
            return -1;
        }

    }

    /**
     * 保存网络图片到本地
     * @param mContext
     * @param url
     * @param listener
     */
    public static void saveImageUrlToGallery(Context mContext, String url,OnListener listener) {
        if (X3StringUtils.isEmpty(url)) {
            return;
        }
        XXPermissions.with(mContext)
                .permission(Permission.Group.STORAGE)
                .request(new OnPermissionCallback() {
                    @Override
                    public void onGranted(List<String> permissions, boolean all) {
                        if(all){
                            Observable.create((ObservableOnSubscribe<File>) e -> {
                                if (url.contains(".mp4") || url.contains(".wav")) {
                                    File fileFromServer = getFileFromServer(mContext,url);
                                    e.onNext(fileFromServer);
                                }else {
                                    if (mContext == null) {
                                        e.onComplete();
                                        return;
                                    }

                                    Bitmap bitmap;
                                    if (url.startsWith("data:")) {
                                        bitmap = stringToBitmap(url);
                                    }else {
                                        bitmap = getHttpBitmap(url);
                                    }

                                    file = X3FileUtils.saveBitmapToCamera(mContext, "mechanic_" + System.currentTimeMillis() + ".jpg", bitmap);
                                    e.onNext(file);
                                }
                                e.onComplete();
                            }).subscribeOn(Schedulers.io())
                                    .observeOn(AndroidSchedulers.mainThread())
                                    .subscribe(file -> {

                                        if (file == null) {
                                            listener.onFail();
                                        }else {
                                            listener.onSuccess();
                                        }
                                    });
                        }else {
                            XXPermissions.startPermissionActivity(mContext,permissions);
                        }
                    }

                    @Override
                    public void onDenied(List<String> permissions, boolean never) {
                        XXPermissions.startPermissionActivity(mContext,permissions);
                    }
                });
    }

    private static Bitmap getHttpBitmap(String url){
        URL myFileUrl = null;
        Bitmap bitmap = null;
        try {
            myFileUrl = new URL(url);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        try {
            HttpURLConnection conn = (HttpURLConnection) myFileUrl.openConnection();
            conn.setDoInput(true);
            conn.connect();
            InputStream is = conn.getInputStream();
            bitmap = BitmapFactory.decodeStream(is);
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return bitmap;
    }

    private static File getFileFromServer(Context mContext,String path) throws Exception {
        // 如果相等的话表示当前的sdcard挂载在手机上并且是可用的
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            URL url = new URL(path);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(5000);
            // 获取到文件的大小
            InputStream is = conn.getInputStream();
            String parentPath = Environment.getExternalStorageDirectory().getPath() + "/DCIM/Camera/";
            File parentFile = new File(parentPath);
            if (!parentFile.exists()) {
                parentFile.mkdirs();
            }

            String filePath = Environment.getExternalStorageDirectory().getPath() + "/DCIM/Camera/" + System.currentTimeMillis() + ".mp4";
            File file = new File(filePath);
            if (!file.exists()) {
                file.createNewFile();
            }

            FileOutputStream fos = new FileOutputStream(file);
            BufferedInputStream bis = new BufferedInputStream(is);
            byte[] buffer = new byte[1024];
            int len;
            while ((len = bis.read(buffer)) != -1) {
                fos.write(buffer, 0, len);
            }
            fos.close();
            bis.close();
            is.close();

            ContentValues values = new ContentValues();
            values.put(MediaStore.Video.Media.DATA, filePath);
            mContext.getContentResolver().insert(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, values);

            return file;
        } else {
            return null;
        }
    }

    /**
     * 复制文件
     *
     * @param source 输入文件
     * @param target 输出文件
     */
    private static void copy(File source, File target) {
        FileInputStream fileInputStream = null;
        FileOutputStream fileOutputStream = null;
        try {
            fileInputStream = new FileInputStream(source);
            fileOutputStream = new FileOutputStream(target);
            byte[] buffer = new byte[1024];
            while (fileInputStream.read(buffer) > 0) {
                fileOutputStream.write(buffer);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                fileInputStream.close();
                fileOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public interface OnListener {
        void onSuccess();

        void onFail();
    }

    /**
     * 压缩图片到目标大小以下
     *
     * @param file
     * @param targetSize
     */
    public static void compressBmpFileToTargetSize(File file, long targetSize) {
        if (file.length() > targetSize) {
            // 每次宽高各缩小一半
            double ratio = 1.5;
            // 获取图片原始宽高
            BitmapFactory.Options options = new BitmapFactory.Options();
            Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath(), options);
            int targetWidth = (int) (options.outWidth / ratio);
            int targetHeight = (int) (options.outHeight / ratio);

            // 压缩图片到对应尺寸
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            int quality = 100;
            Bitmap result = generateScaledBmp(bitmap, targetWidth, targetHeight, baos, quality);

            // 计数保护，防止次数太多太耗时。
            int count = 0;
            while (baos.size() > targetSize && count <= 10) {
                targetWidth /= ratio;
                targetHeight /= ratio;
                count++;

                // 重置，不然会累加
                baos.reset();
                result = generateScaledBmp(result, targetWidth, targetHeight, baos, quality);
            }
            try {
                FileOutputStream fos = new FileOutputStream(file);
                fos.write(baos.toByteArray());
                fos.flush();
                fos.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 图片缩小一半
     *
     * @param srcBmp
     * @param targetWidth
     * @param targetHeight
     * @param baos
     * @param quality
     * @return
     */
    private static Bitmap generateScaledBmp(Bitmap srcBmp, int targetWidth, int targetHeight, ByteArrayOutputStream baos, int quality) {
        Bitmap result = Bitmap.createBitmap(targetWidth, targetHeight, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(result);
        Rect rect = new Rect(0, 0, result.getWidth(), result.getHeight());
        canvas.drawBitmap(srcBmp, null, rect, null);
        if (!srcBmp.isRecycled()) {
            srcBmp.recycle();
        }
        result.compress(Bitmap.CompressFormat.JPEG, quality, baos);
        return result;
    }

    /**
     * 读取sd卡对象
     *
     * @return
     */
    @SuppressWarnings("unchecked")
    public static String readBeanFromSdCard(String path) {
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {  //检测sd卡是否存在

            String content = "";

            File file = new File(path);

            InputStream instream = null;
            try {
                instream = new FileInputStream(file);
                if (instream != null) {
                    InputStreamReader inputreader = new InputStreamReader(instream);
                    BufferedReader buffreader = new BufferedReader(inputreader);
                    String line;
                    //分行读取
                    while ((line = buffreader.readLine()) != null) {
                        content = content + line;
                    }

                    return content;

                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (instream != null) {
                    try {
                        instream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        return null;
    }

    /**
     * 压缩图片
     * @return
     * isBeforeFile 是否输出到原文件中
     */
    public static void saveBitmapCompress(Context mContext,Bitmap bitmap,String savePath, CameraCompressSuccess compressSuccess) {
        if (bitmap == null) {
            compressSuccess.iOnCompressSuccess("");
            return;
        }

        Observable.create((ObservableOnSubscribe<String>) e -> {

            FileOutputStream outputStream = null;

            File mirkFile;

            String currentPath = savePath;

            try {
                if (X3StringUtils.isEmpty(currentPath)) {
                    currentPath = getStoragePath(mContext, X3FileUtils.MECHANIC_PHOTO_STORAGE_PATH) + "work_tain" + System.currentTimeMillis() + ".jpg";
                }

                mirkFile = new File(currentPath);
                if (!mirkFile.exists()) {
                    try {
                        mirkFile.createNewFile();
                    } catch (IOException ioError) {
                        ioError.printStackTrace();
                    }
                }
                outputStream = new FileOutputStream(mirkFile);

                int quality = (int) SpHelper.getData(X3Constent.CAMERA_QUALITY, 50);

                /**
                 * 原图压缩也处理一下 不然太大
                 */
                if (quality == 100) {
                    quality = 95;
                }

                bitmap.compress(Bitmap.CompressFormat.JPEG,quality,outputStream);

                e.onNext(currentPath);

            } catch (FileNotFoundException notError) {
                notError.printStackTrace();
                e.onNext("");
            }finally {
                if (outputStream != null) {
                    try {
                        outputStream.close();
                    } catch (IOException ioError) {
                        ioError.printStackTrace();
                    }
                }
            }
            e.onComplete();
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(path -> {
                    compressSuccess.iOnCompressSuccess(path);
                });
    }

    /**
     * 压缩图片 原图
     * @return
     * isBeforeFile 是否输出到原文件中
     */
    public static void saveOriginBitmapCompress(Context mContext,Bitmap bitmap,String savePath, CameraCompressSuccess compressSuccess) {
        if (bitmap == null) {
            compressSuccess.iOnCompressSuccess("");
            return;
        }

        Observable.create((ObservableOnSubscribe<String>) e -> {

            FileOutputStream outputStream = null;

            File mirkFile;

            String currentPath = savePath;

            try {
                if (X3StringUtils.isEmpty(currentPath)) {
                    currentPath = X3FileUtils.getStoragePath(mContext, X3FileUtils.MECHANIC_PHOTO_STORAGE_PATH) + "work_tain" + System.currentTimeMillis() + ".jpg";
                }

                mirkFile = new File(currentPath);
                if (!mirkFile.exists()) {
                    try {
                        mirkFile.createNewFile();
                    } catch (IOException ioError) {
                        ioError.printStackTrace();
                    }
                }
                outputStream = new FileOutputStream(mirkFile);

                bitmap.compress(Bitmap.CompressFormat.JPEG,100,outputStream);

                e.onNext(currentPath);

            } catch (FileNotFoundException notError) {
                ToastUtils.show("FileNotFoundException");
                notError.printStackTrace();
                e.onNext("");
            }finally {
                if (outputStream != null) {
                    try {
                        outputStream.close();
                    } catch (IOException ioError) {
                        ToastUtils.show("IOException");
                        ioError.printStackTrace();
                    }
                }
            }
            e.onComplete();
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(path -> {
                    compressSuccess.iOnCompressSuccess(path);
                });
    }

    /**
     * 压缩图片
     * @return
     */
    public static void saveFileBitmapCompress(Context mContext,File currentFile, CameraCompressSuccess compressSuccess) {
        if (currentFile == null) {
            compressSuccess.iOnCompressSuccess("");
        }
        if (!currentFile.exists()) {
            compressSuccess.iOnCompressSuccess("");
        }
        Bitmap bitmap = BitmapFactory.decodeFile(currentFile.getPath());

        if (bitmap == null) {
            compressSuccess.iOnCompressSuccess("");
        }

        Observable.create((ObservableOnSubscribe<String>) error -> {

            int bitmapDegree = getBitmapDegree(currentFile.getPath());
            Bitmap newBitmap = bitmap;
            if (bitmapDegree != 0) {
                newBitmap = rotaImageView(bitmapDegree, bitmap);
            }

            FileOutputStream outputStream = null;
            File mirkFile = null;
            try {
                String currentPath = getStoragePath(mContext, X3FileUtils.MECHANIC_PHOTO_STORAGE_PATH) + "work_tain" + System.currentTimeMillis() + ".jpg";
                mirkFile = new File(currentPath);
                if (!mirkFile.exists()) {
                    try {
                        mirkFile.createNewFile();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                outputStream = new FileOutputStream(mirkFile);

                int quality = (int) SpHelper.getData(X3Constent.CAMERA_QUALITY, 50);

                newBitmap.compress(Bitmap.CompressFormat.JPEG,quality,outputStream);

                error.onNext(currentPath);

            } catch (FileNotFoundException e) {
                e.printStackTrace();
                error.onNext("");
            }finally {
                if (outputStream != null) {
                    try {
                        outputStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            error.onComplete();
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(path -> {
                    compressSuccess.iOnCompressSuccess(path);
                });
    }

    /**
     * 压缩图片
     * @return
     * isBeforeFile 是否输出到原文件中
     */
    public static void saveFileBitmapCompress(Context mContext,Bitmap currentBitmap, CameraCompressSuccess compressSuccess) {
        if (currentBitmap == null) {
            compressSuccess.iOnCompressSuccess("");
        }
        Observable.create((ObservableOnSubscribe<String>) error -> {
            FileOutputStream outputStream = null;
            File mirkFile = null;
            try {
                String currentPath = getStoragePath(mContext,MECHANIC_PHOTO_STORAGE_PATH) + "work_tain" + System.currentTimeMillis() + ".jpg";

                mirkFile = new File(currentPath);
                if (!mirkFile.getParentFile().exists()) {
                    mirkFile.getParentFile().mkdirs();
                }
                if (!mirkFile.exists()) {
                    try {
                        mirkFile.createNewFile();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                outputStream = new FileOutputStream(mirkFile);

                int quality = (int) SpHelper.getData(X3Constent.CAMERA_QUALITY, 50);

                currentBitmap.compress(Bitmap.CompressFormat.JPEG,quality,outputStream);

                error.onNext(currentPath);

            } catch (FileNotFoundException e) {
                e.printStackTrace();
                error.onNext("");
            }finally {
                if (outputStream != null) {
                    try {
                        outputStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            error.onComplete();
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(path -> {
                    compressSuccess.iOnCompressSuccess(path);
                });
    }

    private static int getBitmapDegree(String path) {

        int degree = 0;

        try {
            // 从指定路径下读取图片，并获取其EXIF信息
            ExifInterface exifInterface = new ExifInterface(path);
            // 获取图片的旋转信息
            int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION,
                    ExifInterface.ORIENTATION_NORMAL);

            switch (orientation) {
                case ExifInterface.ORIENTATION_ROTATE_90:

                    degree = 90;

                    break;

                case ExifInterface.ORIENTATION_ROTATE_180:

                    degree = 180;

                    break;

                case ExifInterface.ORIENTATION_ROTATE_270:

                    degree = 270;

                    break;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return degree;
    }

    /**
     * 解决部分手机压缩之后会旋转角度的问题
     * @param angle
     * @param bitmap
     * @return
     */
    public static Bitmap rotaImageView(int angle, Bitmap bitmap) {
        Bitmap returnBm = null;
        // 根据旋转角度，生成旋转矩阵
        Matrix matrix = new Matrix();
        matrix.postRotate(angle);
        try {
            // 将原始图片按照旋转矩阵进行旋转，并得到新的图片
            returnBm = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
        } catch (OutOfMemoryError e) {
        }
        if (returnBm == null) {
            returnBm = bitmap;
        }
        if (bitmap != returnBm) {
            bitmap.recycle();
        }
        return returnBm;
    }

    /**
     * 获取本地视频的时长
     * @param videoPath
     * @return
     */
    public static int getLocalVideoDuration(String videoPath) {
        int duration;
        try {
            MediaMetadataRetriever mmr = new  MediaMetadataRetriever();
            mmr.setDataSource(videoPath);
            duration = Integer.parseInt(mmr.extractMetadata
                    (MediaMetadataRetriever.METADATA_KEY_DURATION));
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
        return duration;
    }

    public static Bitmap getImage(String path) throws Exception {
        URL url = new URL(path);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setConnectTimeout(5000);
        conn.setRequestMethod("GET");
        conn.setUseCaches(false);
        InputStream inStream = conn.getInputStream();
        if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
            //return readStream(inStream);
            return BitmapFactory.decodeStream(inStream);

        }
        return null;
    }

    /**
     * 保存文件
     *
     * @param bm
     * @param fileName
     * @throws IOException
     */
    public static boolean saveFile(Bitmap bm, String fileName, String path) {
        File jia = new File(path);
        if (!jia.exists()) {   //判断文件夹是否存在，不存在则创建
            jia.mkdirs();
        }

        File myCaptureFile = new File(jia.getAbsolutePath(), fileName);

        BufferedOutputStream bos = null;
        if (!myCaptureFile.exists()) {
            try {
                myCaptureFile.createNewFile();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        try {
            bos = new BufferedOutputStream(new FileOutputStream(myCaptureFile));
            bm.compress(Bitmap.CompressFormat.PNG, 100, bos);
            bos.flush();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        return false;
    }

    /**
     * 拼接视频
     * @param
     */
    public static boolean appendMovie(String path,List<String> videoList) {
        boolean isSuccess = false;
        try {
            List<Movie> inMovies = new ArrayList();
            for (String videoUri : videoList) {
                inMovies.add(MovieCreator.build(videoUri));
            }

            List<Track> audioTracks = new LinkedList();
            List<Track> videoTracks = new LinkedList<>();

            for (Movie m : inMovies) {
                for (Track t : m.getTracks()) {
                    if ("soun".equals(t.getHandler())) {
                        audioTracks.add(t);
                    }
                    if ("vide".equals(t.getHandler())) {// 从Movie对象中取出视频通道
                        videoTracks.add(t);
                    }
                }
            }

            /**
             * 将视频和音频合并
             */
            Movie resultMovie = new Movie();
            if (!audioTracks.isEmpty()) {
                // 将所有音频通道追加合并
                resultMovie.addTrack(new AppendTrack(audioTracks.toArray(new Track[audioTracks.size()])));
            }
            if (!videoTracks.isEmpty()) {
                // 将所有视频通道追加合并
                resultMovie.addTrack(new AppendTrack(videoTracks.toArray(new Track[videoTracks.size()])));
            }

            Container outContainer = new DefaultMp4Builder().build(resultMovie);// 将结果Movie对象封装进容器
            FileChannel fileChannel = new RandomAccessFile(path, "rw").getChannel();
            outContainer.writeContainer(fileChannel);
            // 将容器内容写入磁盘
            fileChannel.close();
            isSuccess = true;

        } catch (IOException e) {
            isSuccess = false;
            e.printStackTrace();
        }
        return isSuccess;
    }

    public static String getFileName(String pathandname){
        int start=pathandname.lastIndexOf("/");
        if(start != -1 ){
            return pathandname.substring(start+1);
        }else{
            return null;
        }
    }

    /**
     * 截取scrollview的屏幕
     * @param scrollView
     * @return
     */
    public static Bitmap getBitmapByView(ScrollView scrollView) {
        int h = 0;
        Bitmap bitmap = null;
        // 获取scrollview实际高度
        for (int i = 0; i < scrollView.getChildCount(); i++) {
            h += scrollView.getChildAt(i).getHeight();
        }
        // 创建对应大小的bitmap
        bitmap = Bitmap.createBitmap(scrollView.getWidth(), h,
                Bitmap.Config.RGB_565);
        final Canvas canvas = new Canvas(bitmap);
        scrollView.draw(canvas);
        return bitmap;
    }

    public interface CameraCompressSuccess {

        void iOnCompressSuccess(String path);
    }

    /**
     * 删除数据库数据
     */
    public static void deleteDao() {
        DaoSession daoSession = X3MyApp.getInstance().getDaoSession();
        AddTagBeanDao addTagBeanDao = daoSession.getAddTagBeanDao();
        if (addTagBeanDao != null) {
            addTagBeanDao.deleteAll();
        }
        MineRecordBeanDao mineRecordBeanDao = daoSession.getMineRecordBeanDao();
        if (mineRecordBeanDao != null) {
            mineRecordBeanDao.deleteAll();
        }
        AloneImageBeanDao aloneImageBeanDao = daoSession.getAloneImageBeanDao();
        if (aloneImageBeanDao != null) {
            aloneImageBeanDao.deleteAll();
        }
        CustomRecordListBeanDao customRecordListBeanDao = daoSession.getCustomRecordListBeanDao();
        if (customRecordListBeanDao != null) {
            customRecordListBeanDao.deleteAll();
        }
//        AloneServiceListBeanDao aloneServiceListBeanDao = daoSession.getAloneServiceListBeanDao();
//        if (aloneServiceListBeanDao != null) {
//            aloneServiceListBeanDao.deleteAll();
//        }
        AloneSearchBeanDao aloneSearchBeanDao = daoSession.getAloneSearchBeanDao();
        if (aloneSearchBeanDao != null) {
            aloneSearchBeanDao.deleteAll();
        }
        WorkNewImageBeanDao workNewImageBeanDao = daoSession.getWorkNewImageBeanDao();
        if (workNewImageBeanDao != null) {
            workNewImageBeanDao.deleteAll();;
        }
    }

    public static String saveBitmap(Context mContext, Bitmap b) {
        String jpegName = getStoragePath(mContext,MECHANIC_PHOTO_STORAGE_PATH) + "picture_" + new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date()) + ".jpg";
        try {
            FileOutputStream fout = new FileOutputStream(jpegName);
            BufferedOutputStream bos = new BufferedOutputStream(fout);
            b.compress(Bitmap.CompressFormat.JPEG, 100, bos);
            bos.flush();
            bos.close();
            return jpegName;
        } catch (IOException e) {
            e.printStackTrace();
            return "";
        }
    }

    /**
     * 解析base64的图片
     * @param string
     * @return
     */
    public static Bitmap stringToBitmap(String string) {
        Bitmap bitmap = null;
        try {
            byte[] bitmapArray = Base64.decode(string.split(",")[1], Base64.DEFAULT);
            bitmap = BitmapFactory.decodeByteArray(bitmapArray, 0, bitmapArray.length);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bitmap;
    }

    public static String getNetSpeedFilePath(Context mContext) {
        File mirkFile;
        String currentPath = "";
        try {
            if (X3StringUtils.isEmpty(currentPath)) {
                currentPath = X3FileUtils.getStoragePath(mContext, X3FileUtils.NET_CHECK_FILE_PATH) + "net_check.zip";
            }
            mirkFile = new File(currentPath);
            if (!mirkFile.exists()) {
                try {
                    mirkFile.createNewFile();
                } catch (IOException ioError) {
                    ioError.printStackTrace();
                }
            }else{
                mirkFile.delete();
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return currentPath;
    }

}
